# -*- coding: utf-8 -*-
# @Time    : 2023/11/07 10:47
# @Author  : Jonny
# @File    : LuckDingtalkHelperUtils.py
# @Describe: 钉钉 API服务层
import logging
import sqlite3

import pymysql
from contextlib import contextmanager
from timeit import default_timer


@contextmanager
def LuckMysqlHelperUtils(db_host, db_port, db_name, db_user, db_password,
                         commit=True, log_time=True, log_label='总用时'):
    # 如果需要记录时间
    if log_time is True:
        start = default_timer()

    # 通过 connect() 方法获取一个数据库连接，返回 conn
    conn = pymysql.connect(host=db_host, port=db_port, db=db_name,
                           user=db_user, password=db_password)

    # 在进入的时候自动获取cursor
    cursor = conn.cursor(pymysql.cursors.DictCursor)
    # 设置为手动提交
    conn.autocommit(False)
    try:
        yield cursor
    except Exception as e:
        # 如果执行sql语句出现错误，则回滚事务
        logging.error(f'执行sql语句出现错误：{e}')
        conn.rollback()
    else:
        # 提交事务
        conn.commit()
    finally:
        cursor.close()
        conn.close()

        # 如果需要记录时间，在退出的时候打印总耗时
        if log_time is True:
            diff = default_timer() - start
            # logging.INFO('-- %s: %.6f 秒' % (log_label, diff))


@contextmanager
def LuckSqliteHelperUtils(db_name,
                          commit=True, log_time=True, log_label='总用时'):
    # 如果需要记录时间
    if log_time is True:
        start = default_timer()

    # 创建数据库连接
    conn = sqlite3.connect(db_name)

    # 创建光标对象
    cursor = conn.cursor()

    try:
        yield cursor
    except Exception as e:
        # 如果执行sql语句出现错误，则回滚事务
        logging.error(f'执行sql语句出现错误：{e}')
        conn.rollback()
    else:
        # 提交事务
        conn.commit()
    finally:
        cursor.close()
        conn.close()

        # 如果需要记录时间，在退出的时候打印总耗时
        if log_time is True:
            diff = default_timer() - start
            # logging.INFO('-- %s: %.6f 秒' % (log_label, diff))
